<?php

declare(strict_types=1);

namespace App\Repository;
/**
 * 用户数据访问层
 * 作者 薛原
 * 日期 2025-10-17
 */
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use App\Model\User;

class UserRepository
{
    #[Inject]
    private User $userModel;

    /**
     * 创建用户
     * @param array $data
     * @return array
     */
    public function create(array $data):array
    {
        $user = $this->userModel->create($data);
        $user->setHidden(["password"]);
        return $user->toArray();
    }

    /**
     * 查找用户邮件
     * @param string $email
     * @return array
     */
    public function findByEmail(string $email)
    {
        $user = $this->userModel->where("email",$email)->select(["*"])->first();
        if($user){
            return $user->toArray();
        }else{
            return null;
        }
    }

    /**
     * 更新用户登录信息
     * @param int $user_id
     * @param string $ip
     */
    public function updateLoginInfo(int $user_id, string $ip): void
    {
        $this->userModel->where("id",$user_id)->update(["last_login_at"=>Db::Raw("now()"),"last_login_ip"=>$ip]);
    }
    public function getDataById(string $user_id)
    {
        $user = $this->userModel->where("id",$user_id)->select(["*"])->first();
        if($user){
            return $user->toArray();
        }else{
            return null;
        }
    }

    /**
     * 更新用户姓名和头像
     * name 不传则不更新name
     * @param $data
     * @param $user_id
     */
    public function updateNameAndAvatar($data,$user_id)
    {
        $obj = [];
        if(isset($data['name'])){
            $obj['name'] = $data['name'];
        }
        $obj['avatar'] = $data['avatar'];
        $this->userModel->where("id",$user_id)->update($obj);
    }

    /**
     * 合并user数据
     * @param $data
     * @param string $key
     * @return array
     */
    public function mergeUserData($data, $key = "user_id")
    {
        $ids = [];
        foreach($data as $info){
            $ids[] = $info[$key];
        }
        $ids = array_unique($ids);
        if(count($ids) == 0){
            return $data;
        }
        $user_list = $this->userModel->whereIn("id",$ids)->select(["id","name","avatar"])->get()->toArray();
        $user_dic = \App\Lib\DataFormart::dataToDic($user_list);
        foreach($data as $k => $v){
            if(isset($user_dic[$v[$key]])){
                $data[$k]['user'] = $user_dic[$v[$key]];
            }else{
                $data[$k]['user'] = "";
            }
        }
        return $data;
    }
}